{
  "cells": [
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "## 12.10 \u5b9a\u4e49\u4e00\u4e2aActor\u4efb\u52a1\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u95ee\u9898\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4f60\u60f3\u5b9a\u4e49\u8ddfactor\u6a21\u5f0f\u4e2d\u7c7b\u4f3c\u201cactors\u201d\u89d2\u8272\u7684\u4efb\u52a1"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u89e3\u51b3\u65b9\u6848\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "actor\u6a21\u5f0f\u662f\u4e00\u79cd\u6700\u53e4\u8001\u7684\u4e5f\u662f\u6700\u7b80\u5355\u7684\u5e76\u884c\u548c\u5206\u5e03\u5f0f\u8ba1\u7b97\u89e3\u51b3\u65b9\u6848\u3002\n\u4e8b\u5b9e\u4e0a\uff0c\u5b83\u5929\u751f\u7684\u7b80\u5355\u6027\u662f\u5b83\u5982\u6b64\u53d7\u6b22\u8fce\u7684\u91cd\u8981\u539f\u56e0\u4e4b\u4e00\u3002\n\u7b80\u5355\u6765\u8bb2\uff0c\u4e00\u4e2aactor\u5c31\u662f\u4e00\u4e2a\u5e76\u53d1\u6267\u884c\u7684\u4efb\u52a1\uff0c\u53ea\u662f\u7b80\u5355\u7684\u6267\u884c\u53d1\u9001\u7ed9\u5b83\u7684\u6d88\u606f\u4efb\u52a1\u3002\n\u54cd\u5e94\u8fd9\u4e9b\u6d88\u606f\u65f6\uff0c\u5b83\u53ef\u80fd\u8fd8\u4f1a\u7ed9\u5176\u4ed6actor\u53d1\u9001\u66f4\u8fdb\u4e00\u6b65\u7684\u6d88\u606f\u3002\nactor\u4e4b\u95f4\u7684\u901a\u4fe1\u662f\u5355\u5411\u548c\u5f02\u6b65\u7684\u3002\u56e0\u6b64\uff0c\u6d88\u606f\u53d1\u9001\u8005\u4e0d\u77e5\u9053\u6d88\u606f\u662f\u4ec0\u4e48\u65f6\u5019\u88ab\u53d1\u9001\uff0c\n\u4e5f\u4e0d\u4f1a\u63a5\u6536\u5230\u4e00\u4e2a\u6d88\u606f\u5df2\u88ab\u5904\u7406\u7684\u56de\u5e94\u6216\u901a\u77e5\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u7ed3\u5408\u4f7f\u7528\u4e00\u4e2a\u7ebf\u7a0b\u548c\u4e00\u4e2a\u961f\u5217\u53ef\u4ee5\u5f88\u5bb9\u6613\u7684\u5b9a\u4e49actor\uff0c\u4f8b\u5982\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from queue import Queue\nfrom threading import Thread, Event\n\n# Sentinel used for shutdown\nclass ActorExit(Exception):\n    pass\n\nclass Actor:\n    def __init__(self):\n        self._mailbox = Queue()\n\n    def send(self, msg):\n        '''\n        Send a message to the actor\n        '''\n        self._mailbox.put(msg)\n\n    def recv(self):\n        '''\n        Receive an incoming message\n        '''\n        msg = self._mailbox.get()\n        if msg is ActorExit:\n            raise ActorExit()\n        return msg\n\n    def close(self):\n        '''\n        Close the actor, thus shutting it down\n        '''\n        self.send(ActorExit)\n\n    def start(self):\n        '''\n        Start concurrent execution\n        '''\n        self._terminated = Event()\n        t = Thread(target=self._bootstrap)\n\n        t.daemon = True\n        t.start()\n\n    def _bootstrap(self):\n        try:\n            self.run()\n        except ActorExit:\n            pass\n        finally:\n            self._terminated.set()\n\n    def join(self):\n        self._terminated.wait()\n\n    def run(self):\n        '''\n        Run method to be implemented by the user\n        '''\n        while True:\n            msg = self.recv()\n\n# Sample ActorTask\nclass PrintActor(Actor):\n    def run(self):\n        while True:\n            msg = self.recv()\n            print('Got:', msg)\n\n# Sample use\np = PrintActor()\np.start()\np.send('Hello')\np.send('World')\np.close()\np.join()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u8fd9\u4e2a\u4f8b\u5b50\u4e2d\uff0c\u4f60\u4f7f\u7528actor\u5b9e\u4f8b\u7684 send() \u65b9\u6cd5\u53d1\u9001\u6d88\u606f\u7ed9\u5b83\u4eec\u3002\n\u5176\u673a\u5236\u662f\uff0c\u8fd9\u4e2a\u65b9\u6cd5\u4f1a\u5c06\u6d88\u606f\u653e\u5165\u4e00\u4e2a\u961f\u91cc\u4e2d\uff0c\n\u7136\u540e\u5c06\u5176\u8f6c\u4ea4\u7ed9\u5904\u7406\u88ab\u63a5\u53d7\u6d88\u606f\u7684\u4e00\u4e2a\u5185\u90e8\u7ebf\u7a0b\u3002\nclose() \u65b9\u6cd5\u901a\u8fc7\u5728\u961f\u5217\u4e2d\u653e\u5165\u4e00\u4e2a\u7279\u6b8a\u7684\u54e8\u5175\u503c\uff08ActorExit\uff09\u6765\u5173\u95ed\u8fd9\u4e2aactor\u3002\n\u7528\u6237\u53ef\u4ee5\u901a\u8fc7\u7ee7\u627fActor\u5e76\u5b9a\u4e49\u5b9e\u73b0\u81ea\u5df1\u5904\u7406\u903b\u8f91run()\u65b9\u6cd5\u6765\u5b9a\u4e49\u65b0\u7684actor\u3002\nActorExit \u5f02\u5e38\u7684\u4f7f\u7528\u5c31\u662f\u7528\u6237\u81ea\u5b9a\u4e49\u4ee3\u7801\u53ef\u4ee5\u5728\u9700\u8981\u7684\u65f6\u5019\u6765\u6355\u83b7\u7ec8\u6b62\u8bf7\u6c42\n\uff08\u5f02\u5e38\u88abget()\u65b9\u6cd5\u629b\u51fa\u5e76\u4f20\u64ad\u51fa\u53bb\uff09\u3002"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u5982\u679c\u4f60\u653e\u5bbd\u5bf9\u4e8e\u540c\u6b65\u548c\u5f02\u6b65\u6d88\u606f\u53d1\u9001\u7684\u8981\u6c42\uff0c\n\u7c7bactor\u5bf9\u8c61\u8fd8\u53ef\u4ee5\u901a\u8fc7\u751f\u6210\u5668\u6765\u7b80\u5316\u5b9a\u4e49\u3002\u4f8b\u5982\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "def print_actor():\n    while True:\n\n        try:\n            msg = yield      # Get a message\n            print('Got:', msg)\n        except GeneratorExit:\n            print('Actor terminating')\n\n# Sample use\np = print_actor()\nnext(p)     # Advance to the yield (ready to receive)\np.send('Hello')\np.send('World')\np.close()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "### \u8ba8\u8bba\n"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "actor\u6a21\u5f0f\u7684\u9b45\u529b\u5c31\u5728\u4e8e\u5b83\u7684\u7b80\u5355\u6027\u3002\n\u5b9e\u9645\u4e0a\uff0c\u8fd9\u91cc\u4ec5\u4ec5\u53ea\u6709\u4e00\u4e2a\u6838\u5fc3\u64cd\u4f5c send() .\n\u751a\u81f3\uff0c\u5bf9\u4e8e\u5728\u57fa\u4e8eactor\u7cfb\u7edf\u4e2d\u7684\u201c\u6d88\u606f\u201d\u7684\u6cdb\u5316\u6982\u5ff5\u53ef\u4ee5\u5df2\u591a\u79cd\u65b9\u5f0f\u88ab\u6269\u5c55\u3002\n\u4f8b\u5982\uff0c\u4f60\u53ef\u4ee5\u4ee5\u5143\u7ec4\u5f62\u5f0f\u4f20\u9012\u6807\u7b7e\u6d88\u606f\uff0c\u8ba9actor\u6267\u884c\u4e0d\u540c\u7684\u64cd\u4f5c\uff0c\u5982\u4e0b\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "class TaggedActor(Actor):\n    def run(self):\n        while True:\n             tag, *payload = self.recv()\n             getattr(self,'do_'+tag)(*payload)\n\n    # Methods correponding to different message tags\n    def do_A(self, x):\n        print('Running A', x)\n\n    def do_B(self, x, y):\n        print('Running B', x, y)\n\n# Example\na = TaggedActor()\na.start()\na.send(('A', 1))      # Invokes do_A(1)\na.send(('B', 2, 3))   # Invokes do_B(2,3)\na.close()\na.join()"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u4f5c\u4e3a\u53e6\u5916\u4e00\u4e2a\u4f8b\u5b50\uff0c\u4e0b\u9762\u7684actor\u5141\u8bb8\u5728\u4e00\u4e2a\u5de5\u4f5c\u8005\u4e2d\u8fd0\u884c\u4efb\u610f\u7684\u51fd\u6570\uff0c\n\u5e76\u4e14\u901a\u8fc7\u4e00\u4e2a\u7279\u6b8a\u7684Result\u5bf9\u8c61\u8fd4\u56de\u7ed3\u679c\uff1a"
      ]
    },
    {
      "cell_type": "code",
      "execution_count": null,
      "metadata": {},
      "outputs": [],
      "source": [
        "from threading import Event\nclass Result:\n    def __init__(self):\n        self._evt = Event()\n        self._result = None\n\n    def set_result(self, value):\n        self._result = value\n\n        self._evt.set()\n\n    def result(self):\n        self._evt.wait()\n        return self._result\n\nclass Worker(Actor):\n    def submit(self, func, *args, **kwargs):\n        r = Result()\n        self.send((func, args, kwargs, r))\n        return r\n\n    def run(self):\n        while True:\n            func, args, kwargs, r = self.recv()\n            r.set_result(func(*args, **kwargs))\n\n# Example use\nworker = Worker()\nworker.start()\nr = worker.submit(pow, 2, 3)\nworker.close()\nworker.join()\nprint(r.result())"
      ]
    },
    {
      "cell_type": "markdown",
      "metadata": {},
      "source": [
        "\u6700\u540e\uff0c\u201c\u53d1\u9001\u201d\u4e00\u4e2a\u4efb\u52a1\u6d88\u606f\u7684\u6982\u5ff5\u53ef\u4ee5\u88ab\u6269\u5c55\u5230\u591a\u8fdb\u7a0b\u751a\u81f3\u662f\u5927\u578b\u5206\u5e03\u5f0f\u7cfb\u7edf\u4e2d\u53bb\u3002\n\u4f8b\u5982\uff0c\u4e00\u4e2a\u7c7bactor\u5bf9\u8c61\u7684 send() \u65b9\u6cd5\u53ef\u4ee5\u88ab\u7f16\u7a0b\u8ba9\u5b83\u80fd\u5728\u4e00\u4e2a\u5957\u63a5\u5b57\u8fde\u63a5\u4e0a\u4f20\u8f93\u6570\u636e\n\u6216\u901a\u8fc7\u67d0\u4e9b\u6d88\u606f\u4e2d\u95f4\u4ef6\uff08\u6bd4\u5982AMQP\u3001ZMQ\u7b49\uff09\u6765\u53d1\u9001\u3002"
      ]
    }
  ],
  "metadata": {
    "kernelspec": {
      "display_name": "Python 3",
      "language": "python",
      "name": "python3"
    },
    "language_info": {
      "codemirror_mode": {
        "name": "ipython",
        "version": 3
      },
      "file_extension": ".py",
      "mimetype": "text/x-python",
      "name": "python",
      "nbconvert_exporter": "python",
      "pygments_lexer": "ipython3",
      "version": "3.7.1"
    },
    "toc": {
      "base_numbering": 1,
      "nav_menu": {},
      "number_sections": true,
      "sideBar": true,
      "skip_h1_title": true,
      "title_cell": "Table of Contents",
      "title_sidebar": "Contents",
      "toc_cell": false,
      "toc_position": {},
      "toc_section_display": true,
      "toc_window_display": true
    }
  },
  "nbformat": 4,
  "nbformat_minor": 2
}